package course.cmsc436.medicationmanager;

import course.cmsc436.medication.Medication;

import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.google.android.apps.dashclock.ui.SwipeDismissListViewTouchListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;




public class MedicationListActivity extends ListActivity {
	
	
	private String TAG = "MedicationListActivity";

	public  final static String USER_FIRST_NAME ="userFirstName";
	public static final String USER_LAST_NAME ="userLastName";
	public static final String USER_NUMBER ="userNumber";
	public static final String DR_NAME ="physicianName";
	public static final String DR_NUMBER ="physicianNumber";
	
	public String USER_NAME = "user_name";
	
	private String userName;
	private String userNumber;
	
	SharedPreferences prefs;
	
	
	private MedicationListAdapter mAdapter;
	private int editedMed;
	
	
	protected static final int CREATE_NEW_MEDICATION = 0;
	protected static final int VIEW_MEDICATION = 1;
	protected static final int CREATE_NEW_USER = 2;
	
	protected ArrayList<Medication> medList = new ArrayList<Medication>() ;
	protected Medication NewMedAdded= null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		prefs = getPreferences(MODE_PRIVATE);
		
		Log.d(TAG, TAG);
		//user pref
		userName = prefs.getString(USER_NAME, "NA");
		if (userName.equals("NA")){
			startActivityForResult(new Intent(this,
					NewUser.class), CREATE_NEW_USER);
				
		}
		
		setTitle("Welcome "+ userName);
		
		mAdapter = new MedicationListAdapter(getApplicationContext());
		
		mAdapter.setMedicationList(medList);
		
		getListView().setFooterDividersEnabled(true);

		LinearLayout footerView = (LinearLayout) LayoutInflater.from(
				MedicationListActivity.this).inflate(R.layout.footer_view, null);
		getListView().addFooterView(footerView);
		
		footerView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startActivityForResult(new Intent(MedicationListActivity.this,
						NewMedication.class), CREATE_NEW_MEDICATION);
			}
		});
		
		
		SwipeDismissListViewTouchListener dismisser = new SwipeDismissListViewTouchListener(
				this.getListView(),
				new SwipeDismissListViewTouchListener.DismissCallbacks() {
					
					@Override
					public void onDismiss(ListView listView, int[] reverseSortedPositions) {
						for (int position : reverseSortedPositions) {
							mAdapter.removeMed(position);
						}
						mAdapter.notifyDataSetChanged();
					}
					
					@Override
					public boolean canDismiss(int position) {
						return true;
					}
				});
		this.getListView().setOnTouchListener(dismisser);
		this.getListView().setOnScrollListener(dismisser.makeScrollListener());
		
		setListAdapter(mAdapter);
	}
	
	protected void onResume() {
		super.onResume();
		try{
		 medList = MedicationSerializer.getMedications(this.getApplicationContext());
		 if (NewMedAdded != null){
			 medList.add(NewMedAdded);
		 }
		 NewMedAdded = null;
		 mAdapter.setMedicationList(medList);
		}catch(Exception e){
			Log.d(TAG, "could not use MedicationSerializer ");
		}
	}
	
	protected void onPause(){
		super.onPause();
		MedicationSerializer.saveMedications(mAdapter.getMedicationList(),this.getApplicationContext());
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d(TAG, "reach request code");
		if (requestCode == CREATE_NEW_MEDICATION && resultCode == RESULT_OK) {
			//handles new medications
			Medication newMed = new Medication(data.getStringExtra("medName"));
			newMed.setPillsPerDose(data.getIntExtra("pillsPerDose", 0));
			
			Log.d(TAG,"newMed.setPillsPerDose:"+newMed.getPillsPerDose());
			
			newMed.setTimesPerDay(data.getIntExtra("dosesPerDay", 0));
			
			ArrayList<Date> timesDate = new ArrayList<Date>();
			for ( String timeString : data.getStringArrayListExtra("doseTimes")) {
				Calendar c = Calendar.getInstance();
				
				Log.d(TAG,timeString);
				String timeList [] = timeString.split(":");
				Log.d(TAG,"size:"+timeList.length);
				if (timeList.length == 2){
					Log.d(TAG,timeList[0]);
					Log.d(TAG,timeList[1]);
					int hour = Integer.parseInt(timeList[0]);
					int minute  = Integer.parseInt(timeList[1]);
				
					//int hour = Integer.parseInt(timeString.substring(0, 2));
					//int minute = Integer.parseInt(timeString.substring(3, 5));
					c.set(Calendar.HOUR_OF_DAY, hour);
					c.set(Calendar.MINUTE, minute);
					c.set(Calendar.SECOND, 0);
					timesDate.add(c.getTime());
				}
			}
			newMed.setTimes(timesDate);
			
			//schedules alarm if checkbox selected
			if(data.getBooleanExtra("setAlarm", false)) {
				AlarmScheduler.scheduleAlarm(getApplicationContext(), newMed);
			}
			
			Log.d(TAG,newMed.getProprietaryName()+ "addded to list");
			
			NewMedAdded = newMed;
			mAdapter.add(newMed);
			mAdapter.notifyDataSetChanged();
		} 
		else if (requestCode == VIEW_MEDICATION && resultCode == RESULT_OK) {
			//handles medication edits
			Medication edited = mAdapter.getItem(editedMed);
			
			Log.d(TAG,"ppd before " + edited.getPillsPerDose());
			edited.setPillsPerDose(data.getIntExtra("pillsPerDose", 0));
			Log.d(TAG,"ppd after " + edited.getPillsPerDose());
			edited.setTimesPerDay(data.getIntExtra("dosesPerDay", 0));
			
			ArrayList<Date> timesDate = new ArrayList<Date>();
			for ( String timeString : data.getStringArrayListExtra("doseTimes")) {
				Calendar c = Calendar.getInstance();
				
				Log.d(TAG,timeString);
				String timeList [] = timeString.split(":");
				Log.d(TAG,"size:"+timeList.length);
				if (timeList.length == 2){
					Log.d(TAG,timeList[0]);
					Log.d(TAG,timeList[1]);
					int hour = Integer.parseInt(timeList[0]);
					int minute  = Integer.parseInt(timeList[1]);
				
					//int hour = Integer.parseInt(timeString.substring(0, 2));
					//int minute = Integer.parseInt(timeString.substring(3, 5));
					c.set(Calendar.HOUR_OF_DAY, hour);
					c.set(Calendar.MINUTE, minute);
					c.set(Calendar.SECOND, 0);
					timesDate.add(c.getTime());
				}
			}
			edited.setTimes(timesDate);
			
			//schedules alarm if checkbox selected
			if(data.getBooleanExtra("setAlarm", false)) {
				AlarmScheduler.scheduleAlarm(getApplicationContext(), edited);
			}
			
			mAdapter.setMedication(editedMed, edited);
			mAdapter.notifyDataSetChanged();
			MedicationSerializer.saveMedications(mAdapter.getMedicationList(),this.getApplicationContext());
			Log.d(TAG, ""+mAdapter.getItem(editedMed).getPillsPerDose());
		}else if (requestCode == CREATE_NEW_USER && resultCode == RESULT_OK) {
			//handles new users
			
			Log.d(TAG, data.getStringExtra(USER_FIRST_NAME) +", " + data.getStringExtra(NewUser.USER_LAST_NAME));
			
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(this.USER_NAME, data.getStringExtra(USER_FIRST_NAME) + " " + data.getStringExtra(NewUser.USER_LAST_NAME));
			editor.putString(this.USER_NUMBER, data.getStringExtra(this.USER_NUMBER) );
			editor.putString(this.DR_NAME, data.getStringExtra(this.DR_NAME) );
			editor.putString(this.DR_NUMBER, data.getStringExtra(this.DR_NUMBER) );
			
			editor.commit();
			
			userName= data.getStringExtra(USER_FIRST_NAME) +" " + data.getStringExtra(NewUser.USER_LAST_NAME);
			setTitle("Welcome "+ userName);
			
		}
	}

	@Override
	protected void onListItemClick(ListView list, View view, int position, long id) {	
		//start activty for result for possible medication edits
		Log.d(TAG, "item click");
		Medication med = mAdapter.getItem(position);
		Log.d(TAG, "click:"+med.getProprietaryName());
		Intent medInfo = new Intent(MedicationListActivity.this,
				MedicationInfoActivity.class);
		medInfo.putExtra("med",med);
		//keeps track of medication to make edits later if selected
		editedMed = position;
		startActivityForResult(medInfo, VIEW_MEDICATION);
	}
}
